import 'package:flutter/material.dart';
import 'package:metaera_flutter/widgets/KuaixunItem.dart';
import 'package:metaera_flutter/models/ArticleModel.dart';
import 'package:metaera_flutter/services/umeng_analytics.dart';
import 'package:metaera_flutter/widgets/Toasts.dart';
import 'package:metaera_flutter/net/request.dart';

class CategoryPage extends StatefulWidget {
  const CategoryPage({super.key});

  @override
  State<CategoryPage> createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  late List<ArticleModel> _articleLists;
  int _page = 1;
  final int _size = 25;
  bool _hasMore = true;
  bool _isLoading = false;
  late ScrollController _scrollController;

  @override
  void initState() {
    super.initState();
    _articleLists = [];
    _scrollController = ScrollController();
    _scrollController.addListener(_scrollListener);
    _loadNews();
    UmengAnalytics.onPageStart('CategoryPage');
  }

  @override
  void dispose() {
    _scrollController.removeListener(_scrollListener);
    _scrollController.dispose();
    UmengAnalytics.onPageEnd('CategoryPage');
    super.dispose();
  }

  void _scrollListener() {
    // 检查是否滚动到底部
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent - 200) {
      _loadMoreNews();
    }
  }

  Future<void> _refreshNews() async {
    setState(() {
      _page = 1;
      _hasMore = true;
    });
    await _loadNewsData();
  }

  void _loadMoreNews() async {
    if (!_isLoading && _hasMore) {
      setState(() {
        _page++;
      });
      await _loadNewsData();
    }
  }

  Future<void> _loadNews() async {
    setState(() {
      _page = 1;
      _hasMore = true;
    });
    await _loadNewsData();
  }

  Future<void> _loadNewsData() async {
    if (_isLoading) return;

    try {
      setState(() {
        _isLoading = true;
      });

      // 构造请求参数
      Map<String, dynamic> params = {
        'category_id': 0,
        'page': _page,
        'size': _size,
        'type': 2,
      };

      final result = await Request().getArticleList(params);

      if (result['code'] == 200) {
        List<ArticleModel> newNewsList = List<ArticleModel>.from(
          (result['data']['list'] as List).map(
            (item) => ArticleModel.fromJson(item as Map<String, dynamic>),
          ),
        );

        setState(() {
          if (_page == 1) {
            _articleLists = newNewsList;
          } else {
            _articleLists.addAll(newNewsList);
          }

          // 更新是否有更多数据
          _hasMore = newNewsList.length >= _size;
        });
      } else {
        Toasts.error("获取新闻列表失败，请刷新");
      }
    } catch (e) {
      print('Error loading news: $e');
      if (_page > 1) {
        setState(() {
          _page--;
        });
      }
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Widget _buildLoadMoreIndicator() {
    if (!_hasMore) {
      return Container(
        padding: EdgeInsets.all(16),
        alignment: Alignment.center,
        child: Text(
          '没有更多数据了',
          style: TextStyle(color: Colors.grey, fontSize: 14),
        ),
      );
    }

    return Container(
      padding: EdgeInsets.all(16.0),
      alignment: Alignment.center,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(
            width: 20,
            height: 20,
            child: CircularProgressIndicator(
              strokeWidth: 2.0,
              valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
            ),
          ),
          SizedBox(width: 10),
          Text('正在加载更多...', style: TextStyle(color: Colors.grey, fontSize: 14)),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: _refreshNews,
      child: ListView.builder(
        controller: _scrollController,
        itemCount: _articleLists.length + (_hasMore ? 1 : 0),
        itemBuilder: (context, index) {
          if (index == _articleLists.length) {
            return _buildLoadMoreIndicator();
          }

          return ArticleItem(articleModel: _articleLists[index]);
        },
      ),
    );
  }
}
